﻿using System;
using System.Threading;
using System.Windows;
using ttg_internal.utils;

namespace ttg_internal.Utilities.Common
{
    /// <summary>
    /// Base class of WPF UI utility
    /// </summary>
    public abstract class UtilityBase
    {
        // Private fields
        private GlobalInfo _globalInfo;
        private Window _mainView;

        public abstract string Description { get; }

        public abstract string ExternalName { get; }

        public string Name { get; set; }

        public void Init(UtilityProps props, UtilController controller, GlobalInfo info)
        {
            _globalInfo = info;
            ShowMainView();
        }

        public void ActivateOrDeActivate()
        {
            if (IsActive())
            {
                Close();
            }
            else
            {
                ShowMainView();
            }
        }

        public void Close()
        {
            if (IsActive())
            {
                _mainView.Dispatcher.Invoke(new Action(_mainView.Close));
            }
        }

        public bool IsActive()
        {
            return _mainView != null;
        }

        public void Update(float step)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Creates and returns main View
        /// </summary>
        protected abstract Window CreateMainView(GlobalInfo globalInfo);

        /// <summary>
        /// Procedure of utility's GUI thread
        /// </summary>
        private void GuidThreadProc()
        {
            if (Interlocked.CompareExchange(ref _mainView, CreateMainView(_globalInfo), null) != null)
            {
                return;
            }

            _mainView.ShowDialog();
            _mainView = null;
        }

        private void ShowMainView()
        {
            var guiThread = new Thread(GuidThreadProc);
            guiThread.SetApartmentState(ApartmentState.STA);
            guiThread.Start();
        }
    }
}
